//
//  CTCResponderHistoryVC.m
//  ConsultantVersion
//
//  Created by 李小龙 on 2017/3/27.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "CTCResponderHistoryVC.h"
#import "CTCResponderHistoryCell.h"
#import "CTCRapidConsultResultVC.h"

@interface CTCResponderHistoryVC ()
@property (nonatomic, strong) NSMutableArray *questionArr;
/** 页数 */
@property (nonatomic, assign) NSInteger lastIndex;
@end

@implementation CTCResponderHistoryVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self setupNavBar];
    
    [self setupTableView];
    
    [self loadNew];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadRepaidHistoryListRedBadge) name:kReloadRepaidHistoryListRedBadgeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadNew) name:kReloadRepaidHistoryListNotification object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return self.questionArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CTCResponderHistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CTCResponderHistoryCell" forIndexPath:indexPath];
    cell.questionModel = self.questionArr[indexPath.section];
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:@"CTCResponderHistoryCell" cacheByIndexPath:indexPath configuration:^(CTCResponderHistoryCell *cell) {
        cell.questionModel = self.questionArr[indexPath.section];

    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTCRapidConsultResultVC *vc = [[CTCRapidConsultResultVC alloc]init];
    CTCQuestionModel *model = self.questionArr[indexPath.section];
    vc.questionModel = model;
    vc.answerStatus = [model.status integerValue];
    [self.navigationController pushViewController:vc animated:YES];
}



- (void)reloadRepaidHistoryListRedBadge
{
    NSIndexPath *indexPath = self.tableView.indexPathForSelectedRow;
    CTCQuestionModel *model = self.questionArr[indexPath.section];
    model.status = @"1";
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}





- (void)loadNew
{
    self.lastIndex = 1;
    [self.questionArr removeAllObjects];
    [self getResponderHistoryList];
}


- (void)getResponderHistoryList
{
    NSMutableDictionary *paramsDic = [NSMutableDictionary dictionary];
    paramsDic[@"pageIndex"] = @(self.lastIndex);
    paramsDic[@"pageEnd"] = @(self.lastIndex+9);
    
    [MBProgressHUD showAnimationHUD];
    
    [RequestTool POST:kResponderHistoryListUrl
           parameters:paramsDic
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"response %@", responseObject);
                  
                  [self stopRefresh];
                  CTCResponderQuestionListModel *listModel = [CTCResponderQuestionListModel yy_modelWithJSON:responseObject];
                  
                  NSInteger code = [listModel.code integerValue];
                  if (code == 1) {
                      [MBProgressHUD hideHUD];
                      [self.questionArr addObjectsFromArray:listModel.questionArr];
                      self.lastIndex += self.questionArr.count;
                      [self.tableView reloadData];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:listModel.des];
                      if ([listModel.code integerValue] == 2) {
                          CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                          MPWeakSelf(self);
                          vc.loginSuccess = ^(){
                              [weakself loadNew];
                          };
                          [self presentViewController:vc animated:YES completion:nil];
                      }
                  }
                  
              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  [self stopRefresh];
                  DeLog(@"error %@", error);
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
              }];
}



- (void)stopRefresh
{
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
}


- (void)setupNavBar
{
    self.title = @"历史记录";
}


- (void)setupTableView
{
//    self.tableView.estimatedRowHeight = 200;
//    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.sectionHeaderHeight = 10;
    self.tableView.sectionFooterHeight = 0;
    self.tableView.contentInset = UIEdgeInsetsMake(11-35, 0, 0, 0);
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNew)];
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(getResponderHistoryList)];

}


- (NSMutableArray *)questionArr
{
    if (!_questionArr) {
        _questionArr = [NSMutableArray array];
    }
    
    return _questionArr;
}

//
//- (NSInteger)lastIndex
//{
//    if (!_lastIndex) {
//        _lastIndex = 1;
//    }
//    
//    return _lastIndex;
//}


@end
